import { filterAuth, findDicByCode, getDicByKey } from '@/support/common';
import { DeleteOutlined, ExportOutlined } from '@ant-design/icons';
import { Button, Card, message, Popconfirm } from 'antd';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import DetailModal from './detailModal';
import { getMd5, getKeyValueString } from '@/utils/utils';
import MaskText from '@/components/MaskText';
import { getOptAuthHeaders } from '@/utils/common';
import { fingerprintFetch } from '@/utils/request';

const mapStateToProps = (state: any) => ({
  userComment: state.userComment,
  loading: state.loading.effects['userComment/postFetchPage'],
});
class UserComment extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      detailVisible: false,
      detailData: {},
      exportLoading: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/postFetchPage',
      payload: { url: '/userfeedback/usercommentfindbypage' },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/initData',
    });
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'userComment/postFetchPage',
      payload: { url: '/userfeedback/usercommentfindbypage', ...formValues },
    });
  };

  handleDownload = (strUrl: any, name: any) => {
    if (strUrl === null || strUrl === '') {
      message.error('文件缺失，无法下载！');
      return;
    }

    const http = strUrl.split('?')[0];
    const files = http.split('/');
    const fileName = files[files.length - 1];
    name = `${name}.${fileName}`;
    const str = `${window.g.url}/common/download?strUrl=` + strUrl;
    let md5 = getMd5('strUrl=' + strUrl);
    const newOptions: any = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        aLink.href = window.URL.createObjectURL(blob);
        aLink.download = name;
        aLink.click();
        document.body.removeChild(aLink);
      })
      .catch(() => message.error('下载失败，请稍后在试!'));
  };

  // 暂停其它音频播放
  pauseOther = (event: any) => {
    let audios = document.getElementsByName('commentAudio');
    audios.forEach((item: any) => {
      if (item !== event.currentTarget) {
        item.pause();
      }
    });
    event.stopPropagation();
    event.preventDefault();
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/delDataWithRes',
      payload: { url: '/userfeedback/batchdeleteusercomment?sid=' + sid },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          message.success('操作成功！');
          this.handleFlushPage();
        }
      },
    });
  };

  handleBatchDelete = (key: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/delDataWithRes',
      payload: { url: '/userfeedback/batchdeleteusercomment?sid=' + key.join(',') },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          message.success('操作成功！');
          this.handleFlushPage();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
    });
  };

  viewDetail = (record: any) => {
    const { dispatch, projectOptions, dicData } = this.props;
    dispatch({
      type: 'userComment/getDataWithRes',
      payload: { url: '/userfeedback/usercommentfinddetail', sid: record.id },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          let newData = { ...resp.data };
          let curOptions = projectOptions.filter((item: any) => item.value === record.projectId);
          if (curOptions && curOptions.length > 0) {
            newData.projectName = curOptions[0].label;
          }
          newData.feedbackTypeName = getDicByKey(dicData, 'feedbackType', record.feedbackType);
          newData.feedbackSourceType =
            record.feedbackSourceType == 'dfspt' ? '' : record.feedbackSourceType;
          newData.typeSourcesName =
            record.typeSources == 'dfspt'
              ? ''
              : getDicByKey(dicData, 'commentTypeSources', record.typeSources);
          this.setState({ detailVisible: true, detailData: newData });
        }
      },
    });
  };

  changeVisible = () => {
    this.setState({ detailVisible: false, detailData: {} });
  };

  handleExport = () => {
    const { formValues } = this.state;
    const {
      userComment: {
        pageData: { pagination },
      },
    } = this.props;
    if (pagination.total > 5000) {
      message.warning('您目前搜索的结果等于0条或者大于5000条，请选择查询条件，精确查询范围！');
      return;
    }
    const str = `${window.g.url}/userfeedback/exportusercomment`;
    const newOptions: any = {};
    const obj = Object.assign({}, formValues);
    let dataStr = getKeyValueString(obj);
    let md5 = getMd5(dataStr);
    newOptions.method = 'POST';
    newOptions.body = JSON.stringify(obj);
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      ...getOptAuthHeaders(),
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    this.setState({
      exportLoading: true,
    });
    fingerprintFetch(str, newOptions)
      .then(response => {
        this.setState({
          exportLoading: false,
        });
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `用户吐槽列表${new Date().toLocaleDateString()}.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => {
        this.setState({
          exportLoading: false,
        });
        message.error('导出失败，请稍后再试!');
      });
  };

  render() {
    const {
      userComment: {
        pageData: { list, pagination },
      },
      loading,
      pathname,
      projectOptions,
      dicData,
      permissions,
    } = this.props;
    const { formValues, selectedRowKeys, detailVisible, detailData } = this.state;
    const isDel = filterAuth('userComment_doDel', permissions, pathname);
    const isExport = filterAuth('userComment_doExport', permissions, pathname);
    const isDetail = filterAuth('userComment_doDetail', permissions, pathname);
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '问题编码',
        dataIndex: 'infoId',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '所属项目',
        dataIndex: 'projectId',
        render: (text: any) => {
          if (text) {
            let curOptions = projectOptions.filter((item: any) => item.value === text);
            if (curOptions && curOptions.length > 0) {
              return curOptions[0].label;
            } else {
              return text;
            }
          } else {
            return text;
          }
        },
      },
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: 'PDSN',
        dataIndex: 'pdsn',
      },
      {
        title: '手机号码',
        dataIndex: 'mobile',
        render(val: any) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '用户ID',
        dataIndex: 'userId',
        render(val: any) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '吐槽来源',
        dataIndex: 'typeSources',
        render: (text: any, record: any) => {
          if (record.projectId === 'dfspt') {
            return '';
          } else {
            return getDicByKey(dicData, 'commentTypeSources', text);
          }
        },
      },
      {
        title: '吐槽类型',
        dataIndex: 'feedbackSourceType',
        render: (text: any, record: any) => {
          if (record.projectId === 'dfspt') {
            return '';
          } else {
            return text;
          }
        },
      },
      {
        title: '反馈内容',
        dataIndex: 'messageContent',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '吐槽文件',
        dataIndex: 'deflautFile',
        render: (text: any, record: any) => {
          if (text && text.endsWith('.wav')) {
            return (
              <audio
                style={{ width: 250, height: 35 }}
                controlsList="nodownload"
                controls={true}
                name="commentAudio"
                onPlay={this.pauseOther}
              >
                <source src={text} type="audio/mpeg"></source>
                你的浏览器不支持播放音乐，建议使用谷歌浏览器
              </audio>
            );
          } else {
            return isDetail ? <a onClick={() => this.viewDetail(record)}>查看详情</a> : '无权查看';
          }
        },
      },
      // {
      //   title: '问题描述',
      //   dataIndex: 'remark',
      //   render: (text: any) => {
      //     return <Ellipsis length={20} tooltip>{text}</Ellipsis>;
      //   }
      // },
      {
        title: '反馈时间',
        dataIndex: 'clientTime',
      },
      {
        title: '相关系统',
        dataIndex: 'feedbackType',
        render: (text: any) => {
          return getDicByKey(dicData, 'feedbackType', text);
        },
      },
      {
        title: '软件版本',
        dataIndex: 'softVersion',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 184,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'userComment_doDetail',
              onConfirm: () => this.viewDetail(record),
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'userComment_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleDelete(record.id),
            },
          ];
          if (record.deflautFile) {
            btns.push({
              title: '下载',
              key: 'download',
              auth: 'userComment_doDownload',
              Popconfirm: true,
              message: '是否确认下载？',
              onConfirm: () => this.handleDownload(record.deflautFile, record.mobile),
            });
          }
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys: any, rows: any) => {
        this.setState({ selectedRowKeys, selectedRows: rows });
      },
    };
    const tableProps = {
      rowSelection: isDel ? rowSelection : null,
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '手机号码',
        key: 'mobile',
      },
      {
        type: 'select',
        title: '所属项目',
        key: 'projectId',
        selectOptions: projectOptions,
        keyValue: ['value', 'label'],
      },
      {
        type: 'input',
        title: '问题编码',
        key: 'infoId',
      },
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
      },
      {
        type: 'input',
        title: 'PDSN',
        key: 'pdsn',
      },
      {
        type: 'input',
        title: '反馈内容',
        key: 'messageContent',
      },
      {
        type: 'select',
        title: '相关系统',
        key: 'feedbackType',
        selectOptions: findDicByCode(dicData, 'feedbackType'),
        keyValue: ['dictKey', 'dictValue'],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'userComment/postFetchPage',
              url: '/userfeedback/usercommentfindbypage',
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() =>
              this.setState({
                formValues: {},
                selectedRows: [],
                selectedRowKeys: [],
              })
            }
          />
        </Card>
        <Card className={styles.standardTable}>
          {isDel || isExport ? (
            <div className="my_newItem">
              {isDel && selectedRowKeys.length > 0 ? (
                <>
                  <span>已选&nbsp;{selectedRowKeys.length}&nbsp;项&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <Popconfirm
                    title="是否确认删除所选数据？"
                    onConfirm={() => this.handleBatchDelete(selectedRowKeys)}
                  >
                    <Button size="small" type="primary" icon={<DeleteOutlined />} danger>
                      批量删除
                    </Button>
                  </Popconfirm>
                </>
              ) : null}
              {isExport ? (
                <Popconfirm title="是否确认导出数据？" onConfirm={() => this.handleExport()}>
                  <Button
                    size="small"
                    icon={<ExportOutlined />}
                    type="primary"
                    loading={this.state.exportLoading}
                  >
                    导出
                  </Button>
                </Popconfirm>
              ) : null}
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'userComment/postFetchPage',
              url: '/userfeedback/usercommentfindbypage',
            }}
            formValues={formValues}
          />
        </Card>
        <DetailModal visible={detailVisible} data={detailData} changeVisible={this.changeVisible} />
      </div>
    );
  }
}
export default connect(mapStateToProps)(UserComment);
